package com.leetcode.algorithm.y22.m07.w3;

import java.util.ArrayList;
import java.util.List;

/**
 * 989. 数组形式的整数加法
 * 
 * https://leetcode.cn/problems/add-to-array-form-of-integer/
 * 
 * @author jie.deng
 *
 */
class Question0989Solution01 {

	public List<Integer> addToArrayForm(int[] num, int k) {
		int len = num.length;
		int i = len - 1;
		int carry = 0;
		while (k > 0 && i >= 0) {
			int sum = k % 10 + num[i] + carry;
			num[i] = sum % 10;
			carry = sum / 10;

			i--;
			k = k / 10;
		}
		List<Integer> list = new ArrayList<>();
		if (i == -1) {
			for (int j = 0; j < num.length; j++) {
				list.add(num[j]);
			}
			while (k > 0) {
				int sum = k % 10 + carry;
				list.add(0, sum % 10);
				carry = sum / 10;
				k = k / 10;
			}
			if (carry == 1) {
				list.add(0, 1);
			}
		} else {
			if (carry == 1) {
				while (i >= 0 && num[i] == 9) {
					num[i] = 0;
					i--;
				}
				if (i != -1) {
					num[i]++;
					carry = 0;
				}
			}
			for (int j = 0; j < num.length; j++) {
				list.add(num[j]);
			}
			if (carry == 1) {
				list.add(0, 1);
			}
		}
		return list;
	}

}